#include "cmd_handler.h"

#include <getopt.h>
#include <sstream>
#include <vector>
#include <string.h>
using namespace std;

string cmd_handler_t::proc_gmcmd(const char* cmd_, void* gm_)
{
    if (cmd_ == NULL || *cmd_ == 0 || *cmd_ == '\n')
        return "empty command";

    stringstream stm(cmd_);
    vector<string> vec;
    string str;
    char* argv[40];
    memset((void*)argv, 0, sizeof(argv));

    while(stm >> str)
        vec.push_back(str);
    for(int i=0; i<vec.size(); ++i)
        argv[i] = (char*)vec[i].c_str();
    
    string strcmd = vec[0];
    if(_handlers.count(strcmd) == 0)
        return "无效命令";

    const cmd_t &handler = _handlers[vec[0]];
    
    Arg args;
    int cmd;
    char arg[3] = "-x";
    optind = 0;
    while((cmd =getopt_long(vec.size(), argv, handler.opts.c_str(), NULL, NULL))>=0)
    {
        if (cmd == '?')
            continue;

        arg[1] = cmd;
        args.insert(std::make_pair(arg, optarg));
    }

    return handler.handle(args, gm_);
}
